package cn.itcast.jd.task;

import cn.itcast.jd.pojo.Item;
import cn.itcast.jd.service.ItemService;
import cn.itcast.jd.util.HttpUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component
public class ItemTask {

    @Autowired
    private HttpUtils httpUtils;
    @Autowired
    private ItemService itemService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    //    当下载任务完成后，间隔多长时间进行下一次任务
    @Scheduled(fixedDelay = 100 * 1000)
    public void itemTask() throws Exception {

//        声明需要解析的初始地址
        String url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&suggest=1.def.0.base&wq=%E6%89%8B%E6%9C%BA&pvid=a7fd756f08c14a2db82664fb79b24a39&s=56&click=0&page=";
//遍历页面，按照页码对手机的页面进行解析
        for (int i = 1; i < 3; i = i + 2) {
            String html = httpUtils.doGetHtml(url + i);

//            实验解析页面，获取商品数据存储
            this.parse(html);

        }
        System.out.println("手机数据抓取完成！");
    }

    //            实验解析页面，获取商品数据存储
    private void parse(String html) throws IOException {
//获取DOcument
        Document doc = Jsoup.parse(html);

//        获取spu
        Elements spuEles = doc.select("div#J_goodsList>ul>li");
        for (Element spuEle : spuEles) {
//            获取spu
            long spu = Long.parseLong(spuEle.attr("data-spu"));

//        获取sku信息
            Elements skuEles = spuEle.select("li.ps-item");
            for (Element skuEle : skuEles) {
                long sku = Long.parseLong(skuEle.select("[data-sku]").attr("data-sku"));
//           根据sku查询你商品数据
                Item item = new Item();
                item.setSku(sku);
                List<Item> list = this.itemService.findAll(item);
//                如果商品数据就进入下一个循环，如果存在，则不保存

                if (list.size() > 0) {
                    continue;
                }
//设置商品的spu
                item.setSpu(spu);
//商品详细地址
                String itemUrl = "https://item.jd.com/" + sku + ".html";
                item.setUrl(itemUrl);
//获取商品图片,要进行必要的调试
                String picUrl = "https:" + skuEle.select("img[data-sku]").first().attr("data-lazy-img");
                picUrl = picUrl.replace("/n9/", "/n1/");
                String picName = this.httpUtils.doGetImage(picUrl);
                item.setPic(picName);

                //获取商品价格
                String priceJson = this.httpUtils.doGetHtml("https://p.3.cn/prices/mgets?skuIds=J_" + sku);
                double price = MAPPER.readTree(priceJson).get(0).get("p").asDouble();
                item.setPrice(price);

//                获取商品标题
                String itemInfo = this.httpUtils.doGetHtml(item.getUrl());
                Document itemDoc = Jsoup.parse(itemInfo);
                String title = itemDoc.select("div.sku-name").text();
                item.setTitle(title);
                item.setCreated(new Date());
                item.setUpdated(item.getCreated());
                System.out.println("执行");
//                保存商品数据到数据库
                this.itemService.save(item);
            }

        }
    }
}
